package com.nw.dsl4j.generator;

import java.lang.reflect.Field;
import java.lang.reflect.ParameterizedType;
import java.util.Collection;
import java.util.Map;

import org.apache.commons.lang.StringUtils;

public class RefllectionUtils {
	public static Class<?> getType(Field f) {
		if (isCollection(f)) {
			return getCollectionElementType(f);
		} else if (isMap(f)) { 
			return getMapElementType(f);
		} else {
			return f.getType();
		}
	}

	private static Class<?> getMapElementType(Field f) {
		ParameterizedType genericType = (ParameterizedType) f.getGenericType();
		Class<?> type = (Class<?>) genericType.getActualTypeArguments()[1];
		return type;
	}
	public static Class<?> getMapKeyType(Field f) {
		ParameterizedType genericType = (ParameterizedType) f.getGenericType();
		Class<?> type = (Class<?>) genericType.getActualTypeArguments()[0];
		return type;
	}

	public static Class<?> getCollectionElementType(Field f) {
		ParameterizedType genericType = (ParameterizedType) f.getGenericType();
		Class<?> type = (Class<?>) genericType.getActualTypeArguments()[0];
		return type;
	}

	public static boolean isCollection(Field f) {
		return Collection.class.isAssignableFrom(f.getType());
	}
	
	public static String getSetterName(Field f) {
		return "set"+ StringUtils.capitalize(f.getName());
	}

	public static String getGetterName(Field f) {
		return "get"+ StringUtils.capitalize(f.getName());
	}

	public static boolean isMap(Field f) {
		return Map.class.isAssignableFrom(f.getType());
	}


}
